package com.wayin.lift.socket;

import com.wayin.model.ConnectionData;
import com.wayin.model.Picture;
import org.apache.commons.lang.StringUtils;

import javax.imageio.stream.FileImageOutputStream;
import java.io.*;
import java.net.Socket;

/**
 * @Desc 读取客户端数据的线程
 * @author PGQing
 *
 */
public class ReadClientDataThread implements Runnable {
	
	private InputStream is = null;
	
	Socket socket=null;

	public ReadClientDataThread(Socket socket) {
		try {
			is = socket.getInputStream();
			this.socket=socket;

		} catch (IOException e) {
			System.out.println("获取已连接会话中的输入流出现了错误：\n");
			e.printStackTrace();
		}
	}

	//byte数组到图片
	public static void byte2image(byte[] data, String path) {
		if (data.length < 3 || path.equals("")) return;
		try {
			FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
			imageOutput.write(data, 0, data.length);
			imageOutput.close();
			System.out.println("Make Picture success,Please find image in " + path);
		} catch (Exception ex) {
			System.out.println("Exception: " + ex);
			ex.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			int lenght = 0;
			byte[] bytes = new byte[1024];
			String temp = null;
			while ((lenght = is.read(bytes))!=-1) {
				temp = new String(bytes, 0, lenght);
				System.out.println("接收到：" + temp);
				if(temp.equals("ending")) {
					is.close();
					this.socket.close();
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
//		ObjectInputStream is = null;
//		ObjectOutputStream os = null;
//		try {
//			is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
//			os = new ObjectOutputStream(socket.getOutputStream());
//			Object obj = is.readObject();
//			ConnectionData con = (ConnectionData) obj;
//			System.out.println("收到的图片张数为：" + ((con.getPicture_list() == null) ? 0 : (con.getPicture_list().size())));
//			if (StringUtils.isBlank(con.getPath())) {
//				con.setPath("E:\\project\\dyj\\img");
//			}
//			File file = new File(con.getPath());
//			if (!file.exists()) { //如果文件夹不存在
//				file.mkdir(); //创建文件夹
//
//			}
//			if (con.getPicture_list() != null) {
////				PrintUtils printUtils = new PrintUtils();
//				for (Picture p : con.getPicture_list()) {
//					byte2image(p.getPic_data(), con.getPath() + "\\" + p.getPic_name());
////					files.add(new File(con.getPath() + "\\" + p.getPic_name()));
////					printUtils.printSingleFile(new File(con.getPath() + "\\" + p.getPic_name()),1);
//				}
//
//			}
//			os.writeObject(con);
//			os.flush();
//		} catch (IOException ex) {
//			ex.printStackTrace();
//		} catch (ClassNotFoundException ex) {
//			ex.printStackTrace();
//		} finally {
//			try {
//				is.close();
//			} catch (Exception ex) {
//			}
//			try {
//				os.close();
//			} catch (Exception ex) {
//			}
//			try {
//				socket.close();
//			} catch (Exception ex) {
//			}
//		}
	}
	
}
